package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.base.util.PinyinUtil;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.*;
import com.joint.core.service.*;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxEmploymentAction extends BaseFlowAction {

    @Resource
    private EmploymentService employmentService;

    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private NumberCreaterService numberCreaterService;
    @Resource
    private ManageService manageService;
    @Resource
    private InterviewService interviewService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private EmployeesService employeesService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private ReadersService readersService;

    private static String num="10000";

    private Employment employment;
    private Manage manage;
    private Interview interview;
    private String name;
    private String sex;
    private String phone;
    private String departmentName;
    private String departmentId;
    private String postId;
    private String postName;
    private String staffid;
    private Users creater;
    private String createDate;
    private String sexValue;
    private String remark;
    private String nature;
    private String employmentKeyId;
    private String ifCharge;
    private String cardID;
    private Post post;
    private Department department;


    private Users loginUser;
    private ArrayList<Map<String,Object>> nameArrayList;
    private ArrayList<Map<String,Object>> typesArrayList;


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    /**
     * 视图类型
     */
    private String viewtype;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "employment";
    }

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            manage = manageService.get(parentId);
            params.put("manage",manage);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
         LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("2")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=employmentService.findByPagerAndLimit(false, "employment", pager, params);
            }else if(viewtype.equals("3")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=employmentService.findByPagerAndLimit(true, "employment", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=employmentService.findByPagerAndLimit(true, "employment", pager, params);
        }

        List<Employment> eList;
        if (pager.getTotalCount() > 0){
            eList = (List<Employment>) pager.getList();
        }else{
            eList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Employment e:eList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",e.getId());
            rMap.put("name",e.getName());
            rMap.put("sex",e.getSex()==null?"":e.getSex().value());
            rMap.put("department",e.getDepartment()==null?"":e.getDepartment().getName());
            rMap.put("year", DataUtil.DateToString(e.getCreateDate(),"yyyy"));
            rMap.put("month", DataUtil.DateToString(e.getCreateDate(),"MM"));
            rMap.put("state",e.getProcessState()==null?"":e.getProcessState().value());
            String nature =e.getNature();
            if(StringUtils.isNotEmpty(nature)){
                if(nature.equals("0")){
                    rMap.put("nature", "正式");
                }else if(nature.equals("1")){
                    rMap.put("nature", "试用");
                }else{
                   rMap.put("nature", "聘用");
                }

            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 员工个人信息
     * @return
     */
    public String emplist(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            manage = manageService.get(parentId);
            params.put("manage",manage);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        LogUtil.info("viewtype:" + viewtype);
        //已归档
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
        pager=employmentService.findByPagerAndLimit(true, "employment", pager, params);

        List<Employment> eList;
        if (pager.getTotalCount() > 0){
            eList = (List<Employment>) pager.getList();
        }else{
            eList = new ArrayList<>();
        }
        LogUtil.info("elist:" + eList);
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Employment e:eList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",e.getId());
            rMap.put("name",e.getName());
            rMap.put("sex",e.getSex());
            //LogUtil.info("e.getManage():" + e.getManage().getInterviewSet());
            rMap.put("nature",e.getNature());
            rMap.put("title","初级");
            rMap.put("state",e.getProcessState().value());
            rMap.put("year", DataUtil.DateToString(e.getCreateDate(),"yyyy"));
            rMap.put("month", DataUtil.DateToString(e.getCreateDate(),"MM"));
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        LogUtil.info("dataRows"+dataRows);
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            employment = employmentService.get(keyId);
            sexValue=employment.getSex().value();
            createDate=DataUtil.DateToString(employment.getCreateDate(),"yyyy-MM-dd");
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            parentId=employment.getManage().getId();
        }

        return "read";
    }

    /**
     * 是否为面试负责人
     * @return
     */
    public String checkUser(){
        manage = manageService.get(parentId);
        Set<Users> chargeUsers = manage.getChargeUsers();
        loginUser=usersService.getLoginInfo();
        Map<String,String> data=new HashMap<String, String>();
        for (Users users:chargeUsers){
            if(users.equals(loginUser)){
                ifCharge="1";
                data.put("ifCharge",ifCharge);
            }else {
                data.put("ifCharge",ifCharge);

            }
        }

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 新建／修改
     * @return
     */
    public String input(){
        loginUser = usersService.getLoginInfo();
        if (StringUtils.isNotEmpty(keyId)){
            employment= employmentService.get(keyId);
            creater=employment.getCreater();
            post=employment.getPost();
            sexValue = employment.getSex().value();
            sex = employment.getSex().name();
            department=employment.getDepartment();
            createDate= DataUtil.DateToString(employment.getCreateDate(),"yyyy-MM-dd");
        } else {
            if(StringUtils.isNotEmpty(parentId)) {
                manage = manageService.get(parentId);
                Map<String, Object> rMap = null;
                sexValue = manage.getSex().value();
                sex = manage.getSex().name();
                post=manage.getPost();
                department=manage.getRecruitDepart();

            }
            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }

        return "input";
    }


    private void setData(){

        if(StringUtils.isNotEmpty(keyId)){
            employment = employmentService.get(keyId);
        }else{
            employment = new Employment();
            employment.setCreater(usersService.getLoginInfo());
        }
        manage = manageService.get(parentId);
        employment.setManage(manage);
        if(StringUtils.isNotEmpty(departmentId)){
            employment.setDepartment(departmentService.get(departmentId));
        }
        if(StringUtils.isNotEmpty(postId)){
            employment.setPost(postService.get(postId));
        }

        Calendar c = Calendar.getInstance();

        employment.setStaffid(numberCreaterService.getNumber(Employment.class.getName(), c.get(Calendar.YEAR) + "", 4, null));

        employment.setCardID(cardID);
        employment.setName(name);
        employment.setSex(BaseEnum.SexEnum.valueOf(sex));
        employment.setNature(nature);
        employment.setPhone(phone);
        employment.setEdu(manage.getEdu()==null?"":manage.getEdu());
        employment.setRemark(remark);
        employment.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                employmentService.update(employment);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                employmentService.save(employment, "employment", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);

        ArrayList<String> list=new ArrayList<String>();
        Set<Users> usersSet= Sets.newHashSet();

        //Set<Duty> dutySet = employment.getManage().getCreater().getDutySet();
        Department department = manage.getRecruitDepart();
        Set<Power> powerSet = department.getPowerSet();
        LogUtil.info("powerSet"+powerSet);
        for (Power power:powerSet){
            Post post = power.getPost();
            LogUtil.info("post"+post.getName());

            if(StringUtils.equals(post.getName(),"人事负责人")){
                List<Users> persons = dutyService.getPersons(department, post);
                for (Users users:persons){
                    list.add(users.getId());
                    LogUtil.info("QQQ"+list);
                }
            }
        }

        var2.put("examine", list);

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                employmentService.approve(employment, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
               keyId= employmentService.commit(employment, "employment", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }


        Set<Users> usersList = employment.getManage().getChargeUsers();
        for(Users users:usersList){
            usersSet.add(users);
            //LogUtil.info("++++"+usersSet);
        }
        //增加归档后读者
        for(Users users:usersSet){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("employment");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批1
     * @return
     */
    public String approve1(){
        employment = employmentService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                employmentService.approve(employment, FlowEnum.ProcessState.Finished, var1, curDutyId, comment);
                LogUtil.info("employment"+employment);
                Employment entity=employmentService.get(keyId);
                Employees employees = new Employees();
                Manage manage =entity.getManage();
                Set<Interview> interviewSet = manage.getInterviewSet();
                for (Interview interview:interviewSet){
                    if(StringUtils.equals(interview.getName(),entity.getName())){
                        String id = interview.getId();
                        Interview interview1 = interviewService.get(id);
                        interview1.setIfGot(0);
                        interviewService.update(interview1);

                    }

                }

                employees.setName(entity.getName());
                //employees.setSex(BaseEnum.SexEnum.valueOf(entity.getSex().name()));
                employees.setAge(manage.getAge());
                String depId = employment.getDepartment().getId();
                String postId = employment.getPost().getId();
                if(StringUtils.isNotEmpty(depId)){
                    employees.setDep(departmentService.get(depId));
                }
                if(StringUtils.isNotEmpty(postId)){
                    employees.setEmpPost(postService.get(postId));
                }
                Users user = new Users();
                user.setName(employees.getName());
                user.setMobile(employment.getPhone());
                user.setPassword("pass");
                user.setState(BaseEnum.StateEnum.Enable);
                user.setPinYin(PinyinUtil.getPingYin(employees.getName()));
                user.setPinYinHead(PinyinUtil.getPinYinHeadChar(employees.getName()));
                String id = usersService.registerUserAndAdmin( user,usersService.getCompanyByUser()).getId();

                Users users = usersService.get(id);
                Department department=entity.getDepartment();
                Post post = entity.getPost();
                Power power = powerService.getPowerByDepartAndPost(department, post);
                Duty duty=new Duty(users,power,department,post);
                duty.setCompany(usersService.getCompanyByUser());
                duty.setDutyState(EnumManage.DutyState.Default);
                dutyService.save(duty);
                if(StringUtils.isNotEmpty(id)){
                    employees.setUsers(usersService.get(id));
                }
                employees.setCreater(users);
                employees.setProfession(manage.getProfession());
                employees.setCardID(employment.getCardID());
                employees.setNature(employment.getNature());
                employees.setEmployment(entity);
                employees.setStaffid(entity.getStaffid());
                employees.setCompany(usersService.getLoginInfo().getCompany());
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                employeesService.save(employees,"employees",various);

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public Employment getEmployment() {
        return employment;
    }

    public void setEmployment(Employment employment) {
        this.employment = employment;
    }

    public Manage getManage() {
        return manage;
    }

    public void setManage(Manage manage) {
        this.manage = manage;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getNature() {
        return nature;
    }

    public void setNature(String nature) {
        this.nature = nature;
    }

    public Interview getInterview() {
        return interview;
    }

    public void setInterview(Interview interview) {
        this.interview = interview;

    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public String getStaffid() {
        return staffid;
    }

    public void setStaffid(String staffid) {
        this.staffid = staffid;
    }

    public ArrayList<Map<String, Object>> getNameArrayList() {
        return nameArrayList;
    }

    public void setNameArrayList(ArrayList<Map<String, Object>> nameArrayList) {
        this.nameArrayList = nameArrayList;

    }

    public ArrayList<Map<String, Object>> getTypesArrayList() {
        return typesArrayList;
    }

    public void setTypesArrayList(ArrayList<Map<String, Object>> typesArrayList) {
        this.typesArrayList = typesArrayList;
    }

    public void setPostName(String postName) {
        this.postName = postName;
    }

    public String getPostName() {
        return postName;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public String getSexValue() {
        return sexValue;
    }

    public void setSexValue(String sexValue) {
        this.sexValue = sexValue;
    }
    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public String getEmploymentKeyId() {
        return employmentKeyId;
    }

    public void setEmploymentKeyId(String employmentKeyId) {
        this.employmentKeyId = employmentKeyId;
    }

    public String getIfCharge() {
        return ifCharge;
    }

    public void setIfCharge(String ifCharge) {
        this.ifCharge = ifCharge;
    }

    public String getCardID() {
        return cardID;
    }

    public void setCardID(String cardID) {
        this.cardID = cardID;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

}
